package com.jsoft.android.as;

import java.util.HashMap;
import java.util.Map;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


public class LP extends ListActivity {
	
	public String mFusionTable = "";
	public String[] mFusionRow = null;
	
	public static String[] elements = null;
	public Map<String, String[]> mPickers = new HashMap<String, String[]>();

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.main);
        
        Log.d("lp ", "starting");

        
        String who = "empty";
        Bundle extras = getIntent().getExtras();
        mFusionTable = "picker,elements\n"
        	+ "firstpicker,red,green,blue\n"
        	+ "red,orange,pink"
        	;
        if (extras != null) {
                String extrasWho = extras.getString("listpickerCSV");  // ExtraKey
                if (extrasWho != null) {
                	mFusionTable = extrasWho;
                    Log.d("length of mFusionTable ", Integer.toString(mFusionTable.length()));
                }

                if (who != null) {
                        who = extrasWho;
                }

        }
        
        // passed in
        //mFusionTable = "\"picker\",\"elements\"\r\n\"firstpicker\",\"Lightning,Sazh,Snow,Hope,Vanelle,Fang\"\r\n\"Lightning\",\"Blazefire Saber,Axis Blade,Edged Carbine,Lifesaber,Gladius,Organyx,Hauteclaire,Lionheart\"";
        
        // from CSV from spreadsheet
        /*
        mFusionTable = "picker,elements\r\n"
        	+ "firstpicker," + "Lightning,Sazh,Snow,Hope,Vanelle,Fang\r\n"
        	+ "Lightning," + "Blazefire Saber,Axis Blade,Edged Carbine,Lifesaber,Gladius,Organyx,Hauteclaire,Lionheart\r\n"
        	+ "Sazh," + "Vega 42s,Spica Defenders,Deneb Duelers,Rigels,Aldebarans,Pleiades Hi-Powers,Antares Deluxes,Procyons\r\n"
        	+ "Snow," + "Wild Bear,Paladin,Rebel Heart,Power Circle,Feymark,Sacrificial Circle,Unsetting Sun,Umbra\r\n"
        	+ "Hope," + "Airwing,Hawkeye,Otshirvani,Ninurta,Vidofnir,Simurgh,Malphas,Alicanto\r\n"
        	+ "Vanelle," + "Binding Rod,Tigerclaw,Healer's Staff,Pearlwing Staff,Rod of Thorns,Mistilteinn,Belladonna Wand,Heavenly Axis\r\n"
        	+ "Fang," + "Bladed Lance,Dragoon Lance,Partisan,Shamanic Spear,Punisher,Pandoran Spear,Taming Pole,Gae Bolg"
        	;
        	*/

        // split the table up into our temporary rows
        String[] tRows = mFusionTable.split("\n");
        //String[] tRows = mFusionTable.split("\r\n");
        String[] t = null;
        String[] tRow = null;
              
        Log.d("length of tRows ", Integer.toString(tRows.length));

        // get each row and put it into the map
        for (int i = 0; i < tRows.length; i++) {
        	t = tRows[i].split(",", 2);
        	tRow = t[1].split(",");
        	// Arrays.copyOfRange(tRow, 1, tRow.length)
        	// sigh
        	if (tRow.length > 1) {
        		if (tRow[0].startsWith("\"")) {
        			tRow[0] = tRow[0].substring(1);
        		}
        		if (tRow[tRow.length - 1].endsWith("\"")) {
        			tRow[tRow.length - 1] = tRow[tRow.length - 1].substring(0,tRow[tRow.length - 1].length()-1);
        		}        	
        	}
        	
        	//String[] tsa = null;
        	//System.arraycopy(tRow, 1, tsa, 0, tRow.length - 1);
        	Log.d("next key ", t[0]);
        	mPickers.put(t[0], tRow);
        }

        // check that we have the right header in the first line
        // mPickers.get("picker")
        // check the second line is 'firstpicker'
        // set the second line
        Log.d("length of elements ", "about to set");

        elements = mPickers.get("firstpicker");
        Log.d("length of elements ", Integer.toString(elements.length));
        //elements = getResources().getStringArray(R.array.characters_array);
        
        //setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, CHARACTERS));
        //////String[] characters = getResources().getStringArray(R.array.characters_array);
        //setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, characters));
        
        setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, elements));
        
        ListView lv = getListView();
        //lv.setTextFilterEnabled(true);

        lv.setOnItemClickListener(new OnItemClickListener() {
          public void onItemClick(AdapterView<?> parent, View view,
              int position, long id) {
            // When clicked, show a toast with the TextView text
            //String who = (String) ((TextView) view).getText();
            CharSequence who = ((TextView) view).getText();
            Toast.makeText(getApplicationContext(), who, Toast.LENGTH_SHORT).show();
            
            // if the result is in the rest of the pickers, do it again
            
            int requestCode = 111;
            ///if ("Lightning".equals(who)) {
            	elements = mPickers.get(who);
            	Toast.makeText(getApplicationContext(), "off to pick a weapon", Toast.LENGTH_SHORT).show();
            	Intent myIntent = new Intent();
				myIntent.setClassName("com.jsoft.android.as", "com.jsoft.android.as.LP1"); 
				//startActivity(myIntent);
				startActivityForResult(myIntent, requestCode); // fixme
            //}
            
          }
        });
    }
    
    protected void onActivityResult(int requestCode, int resultCode,
            Intent result) {
        if (requestCode == 111) {
            if (resultCode == RESULT_OK) {
                // A weapon was picked.
                Bundle x = result.getExtras();
            	//Intent.setType("type..."); // http://developer.android.com/reference/android/content/Intent.html#setType(java.lang.String)
            	//Intent.setData("uri"); // http://developer.android.com/reference/android/content/Intent.html#setData(android.net.Uri)
            	Bundle bundle = new Bundle();
            	//bundle.putCharSequence("APP_INVENTOR_RESULT", ((TextView) view).getText());
            	bundle.putCharSequence("APP_INVENTOR_RESULT", x.getCharSequence("what"));
            	Intent mIntent = new Intent();
                mIntent.putExtras(bundle);
                setResult(RESULT_OK, mIntent);
                finish();            }
        }
    }
    /*
     * 
     static final String[] CHARACTERS = new String[] {
        "Lightning","Sazh", "Snow"
     };
     */
}